package com.fy.controller;

import com.fy.config.FileConfig;
import com.fy.utils.FileUtil;
import com.fy.utils.FileUtils;
import com.fy.utils.tessdata.TesseractUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 上传图片用
 * 
 * @ClassName com.supergenius.sns.image.controller.UploadImageContoller
 * @description
 * @author : qinggang.liu bis@foxmail.com
 * @Create Date : 2014-1-11 下午2:42:03
 */
@Controller
@RequestMapping("/upload")
public class UploadImageController extends BaseController {

    public static int CUS_PHOTO_WIDTH = 150;
    public static int CUS_PHOTO_HEIGHT = 150;

    private static Logger logger = LoggerFactory.getLogger(UploadImageController.class);

    public static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    public static JsonParser jsonParser = new JsonParser();


    @Autowired
    private FileConfig fileConfig;



    /**
     * OPTION验证
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value="/webuploader", method = RequestMethod.OPTIONS)
    public void webUploader(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Credentials", "false");
        response.setHeader("Access-Control-Allow-Origin", "*"); //生产环境绝对不允许设置为“*”
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
    }

    /**
     * webuploader使用上传文件
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/webuploader", method = RequestMethod.POST)
    @ResponseBody
    public String webuploader(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 跨域设置
            response.setHeader("Access-Control-Allow-Origin", "*"); //生产环境绝对不允许设置为“*”
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile imgFile = multipartRequest.getFile("fileupload");
            // 过滤文件
            if(!FileUtils.accept(imgFile.getOriginalFilename())){
                logger.info("File: " + imgFile.getOriginalFilename() + " is illegal file.");
                return null;
            }
            String[] paths = FileUtil.getSavePathByRequest(request,fileConfig);
            JsonObject json = FileUtil.saveCommonFile(imgFile, paths);
            logger.info("++++upload img return:" + json.get("url").getAsString());
            return json.get("url").getAsString();
        } catch (Exception e) {
            logger.error("webuploader error", e);
        }
        return null;
    }


    @RequestMapping(value = "/getImageContent")
    @ResponseBody
    @CrossOrigin
    public String getImageContent(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 跨域设置
//            response.setHeader("Access-Control-Allow-Origin", "*"); //生产环境绝对不允许设置为“*”
//            response.setHeader("Access-Control-Allow-Methods", "*");
//            response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
//            response.setContentType("application/json");
//            response.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-type", "text/html,charset=utf-8");



            String rootpath = fileConfig.getProfile() + "/";
            String path = request.getParameter("path");
            if(StringUtils.isNotEmpty(path)){
                String allPath = rootpath + path;
                //String content = TessDataUtil.readImageText(rootpath + path);
                String content = TesseractUtil.readImage(rootpath + path, allPath.substring(0,allPath.lastIndexOf("/")));
                return content;
            }else{
                return null;
            }

        } catch (Exception e) {
            logger.error("getImageContent error", e);
        }
        return null;
    }


}